<?php

/**
 * stock actions.
 *
 * @package    Porba
 * @subpackage stock
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class stockActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
        //Filters
        $this->filterParts = new PartFormFilter;
        $this->filterProducts = new ProductFormFilter;
    
        //Products
        $this->pagerProducts = new sfDoctrinePager('Product', sfConfig::get('app_max_items_on_page'));
        $this->pagerProducts->setPage($request->getParameter('pageproduct', 1));
        $this->pagerProducts->init();

        //Materials
        $this->pagerParts = new sfDoctrinePager('Part', sfConfig::get('app_max_items_on_page'));
        $this->pagerParts->setPage($request->getParameter('pagepart', 1));
        $this->pagerParts->init();        
          
  }
  
  public function executeFilterPnP(sfWebRequest $request) {
        //display the results with the Symfony pager object.
        $this->filterParts = new PartFormFilter;
        $this->filterParts->bind($request->getParameter($this->filterParts->getName()));
        $this->pagerParts = new sfDoctrinePager('Part', sfConfig::get('app_max_items_on_page'));
        $this->pagerParts->setQuery($this->filterParts->getQuery());
        $this->pagerParts->setPage($request->getParameter('pagepart', 1));
        $this->pagerParts->init();

         //display the results with the Symfony pager object.
        $this->filterProducts = new ProductFormFilter;
        $this->filterProducts->bind($request->getParameter($this->filterProducts->getName()));
        $this->pagerProducts = new sfDoctrinePager('Product', sfConfig::get('app_max_items_on_page'));
        $this->pagerProducts->setQuery($this->filterProducts->getQuery());
        $this->pagerProducts->setPage($request->getParameter('pageproduct', 1));
        $this->pagerProducts->init();
        
        //refer back to the index template
        $this->setTemplate('index');
    }
    
    public function executeEditPart(sfWebRequest $request) {
        $this->forward404Unless($part = PartTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object part does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'parts';
        $this->form = new PartForm($part);
        
        $this->showEmptyMsg = false;
        $this->showMaterialMsg = false;

        $this->setTemplate('edit');
    }
    
    public function executeShowHistoryPart(sfWebRequest $request) {
        $this->forward404Unless($part = PartTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object part does not exist (%s).', $request->getParameter('id')));
        $this->version = 'materialHistory';        
        $this->materialHistory = MaterialHistoryTable::getInstance()->findBy('material_id', $part->getId());
        
        $this->setTemplate('show');
    }
    
    public function executeShowHistoryProduct(sfWebRequest $request) {
        $this->forward404Unless($product =ProductTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object part does not exist (%s).', $request->getParameter('id')));
        $this->version = 'productHistory';
        $this->productHistory = ProductHistoryTable::getInstance()->findBy('product_id', $product->getId());
        
        $this->setTemplate('show');
    }
    
    public function executeUpdatePart(sfWebRequest $request) {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($part = PartTable::getInstance()->find(array($request->getParameter('id'))), sprintf('Object part does not exist (%s).', $request->getParameter('id')));
        $this->tab = 'parts';
        $this->form = new PartForm($part);
        
        $this->showEmptyMsg = false;
        $this->showMaterialMsg = false;

        $this->processFormPartEdit($request, $this->form);

        $this->setTemplate('edit');
    }
    
    /**
     * Process the material put in production
     * First check if it is allowed for the entered order number and then adjust the stock
     * @param sfWebRequest $request
     * @param sfForm $form 
     */
    protected function processFormPartEdit(sfWebRequest $request, sfForm $form){
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $part = $form->save();

            $production = $_POST['production'];
            $orderid = $_POST['orderno'];
            
            if($orderid != null){
                //Check is the entered order number exists             
                $order = _OrderTable::getInstance()->findOneBy('id', $orderid);
                if($order == null){
                    $this->showEmptyMsg = true;
                    $this->showMaterialMsg = false;
                }
                //Check the status and category to see if it is allowed to put material in production for this order 
                else if(($order->getCategoryName() == 'customer order' && $order->getStatus() == 'collected') || 
                        $order->getCategoryName() == 'stock order' && $order->getStatus() == 'ready' ||
                        $order->getCategoryName() == 'return order'){
                    $this->showEmptyMsg = false;
                    $this->showMaterialMsg = true;
                }
                else{
                    //Check if the edited part belongs to the entered order
                    $reservedlines = ReservedlineTable::getInstance()->findBy('order_id', $orderid);
                    $inlist = false;
                    foreach($reservedlines as $line){
                        if($line->getMaterialId() == $part->getId()){
                            $inlist = true;
                            $reservedline = $line;
                            break;
                        }
                    }
                    if($inlist == true){
                        //enter the production amount in the reservedline table
                        //and transfer the amount from reserved to production in part
                        $lineProduction = $reservedline->getProduction() + $production;
                        ReservedlineTable::setProduction($part->getId(), $orderid, $lineProduction); 
                        $in_production = $part->getInProduction() + $production;
                        $part->setInProduction($in_production);
                        
                        //Add the production to the material history
                        $historyLine = new MaterialHistory();
                        $historyLine->setMaterialId($part->getId());
                        $historyLine->setProduction($production);
                        $historyLine->setOrderId($orderid);
                        $historyLine->setStock(($part->getStock()+$part->getReserved())-$production);
                        $historyLine->save();

                        //If the production amount is greater then the reserved amount for the specific order the reserved amount becomes 0
                        //and the rest gets subtracted from the total stock
                        $reservedAmount = $reservedline->getReserved();
                        if($production > $reservedAmount){
                            $reservedline->setReserved(0);
                            $reservedline->save();
                            $stockreduction = $production - $reservedAmount;
                            $reserved = $part->getReserved() - $reservedAmount;
                            $part->setReserved($reserved);
                            $newStock = $part->getStock() - $stockreduction;
                            $part->setStock($newStock);
                            $part->save();
                        }
                        //if the production amount is less then the reserved amount for the specific order
                        //the production amount gets subtracted from the reserved amount
                        else{
                            $reservedline->setReserved($reservedAmount - $production);
                            $reservedline->save();
                            $part->setReserved($part->getReserved() - $production);
                            $part->save();
                        }

                        $this->showEmptyMsg = false;
                        $this->showMaterialMsg = false;

                        $this->redirect('stock_index');
                    }
                    else{
                        //enter a new line in the reservedline table
                        $reservedLine = new Reservedline();
                        $reservedLine->setOrderId($orderid);
                        $reservedLine->setMaterialId($part->getId());
                        $reservedLine->setProduction($production);
                        $reservedLine->save();
                        
                        //Adjust the stock and production amount of the material
                        $part->setInProduction($part->getInProduction() + $production);
                        $part->setStock($part->getStock() - $production);
                        $part->save();
                        
                        //Add the production to the material history
                        $historyLine = new MaterialHistory();
                        $historyLine->setMaterialId($part->getId());
                        $historyLine->setProduction($production);
                        $historyLine->setOrderId($orderid);
                        $historyLine->setStock(($part->getStock()+$part->getReserved())-$production);
                        $historyLine->save();

                        $this->showEmptyMsg = false;
                        $this->showMaterialMsg = false;

                        $this->redirect('stock_index');
                    }
                }
            } else { 
                $this->showEmptyMsg = true;
                $this->showMaterialMsg = false;
            }
            $this->setTemplate('edit');
        }
    }
}
